// 发起收款弹窗-选择收款阶段

import Taro from "@tarojs/taro";
import { View } from "@tarojs/components";

import ByCol from "@/components/ui/ByCol";
import ByRow from "@/components/ui/ByRow";
import ByText from "@/components/ui/ByText";
import ByButton from "@/components/ui/ByButton";
import ListView from "@/components/app/ListView";
import PopupContainer from "@/components/app/PopupContainer";

import useFetch from "@/hooks/useFetch";
import useList from "@/hooks/useList";
import ApiFinance from "@/api/finance";

import { ReceiptItems } from "@/types/finance";
import { ByPopupBottomEvent } from "@/components/ui/ByPopupBottom";
import { RegMoney } from "@/utils/reg";

export default ({
  intentCustomerId,
  onConfirm,
  onCancel,
}: {
  intentCustomerId: number;
  onConfirm: () => void;
} & ByPopupBottomEvent) => {
  // 拉取列表
  const { loading, list } = useList<ReceiptItems>(ApiFinance.pendingItems, {
    defaultParams: [{ intentCustomerId }],
  });

  const { run } = useFetch(ApiFinance.receiptCreate, "POST", {
    manual: true,
    onSuccess() {
      Taro.showToast({ title: "操作成功" });
      setTimeout(() => {
        onConfirm();
      }, 1500);
    },
  });

  const handleSubmit = async (item) => {
    // @ts-expect-error
    const { content, confirm } = await Taro.showModal({
      title: `${item.itemName}收款`,
      // @ts-expect-error
      editable: true,
      content: item.amount.toFixed(2) + "",
      placeholderText: "请输入收款金额",
      confirmText: "发起",
      confirmColor: "#1677ff",
    });

    if (confirm) {
      if (!RegMoney.test(content) || Number(content) <= 0) {
        Taro.showToast({ icon: "none", title: "收款金额值不正确" });
        setTimeout(() => {
          handleSubmit(item);
        }, 1000);
        return;
      }

      run({
        intentCustomerId,
        amount: Number(content),
        templateDetailId: item.templateDetailId,
      });
    }
  };

  return (
    <PopupContainer title="发起收款" onCancel={onCancel}>
      <View className="p-3 h-[65vh] overflow-auto">
        <ListView loading={loading} isEmpty={list.length === 0}>
          {list.map((item) => (
            <ByRow className="mb-3" key={item.templateDetailId}>
              <ByCol span={5}>
                <ByText size="lg">{item.itemName}</ByText>
              </ByCol>
              <ByCol span={4}>
                <ByText size="lg">￥{item.amount?.toFixed(2)}</ByText>
              </ByCol>
              <ByCol span={3} className="text-right">
                <ByButton
                  loading={loading}
                  onClick={() => handleSubmit(item)}
                >
                  发起
                </ByButton>
              </ByCol>
            </ByRow>
          ))}
        </ListView>
      </View>
    </PopupContainer>
  );
};
